import React, { createContext, useContext, useState, ReactNode } from 'react';

interface ModalContextProps {
  showModal?: (message: string, onConfirm: () => void, onCancel?: () => void) => void;
  hideModal?: () => void;
  modalContent?: ReactNode | null;
  isVisible?: boolean;
  children?: ReactNode;
}

const ModalContext = createContext<ModalContextProps | undefined>(undefined);

export const ModalProvider: React.FC = ({ children }: ModalContextProps) => {
  const [modalContent, setModalContent] = useState<ReactNode | null>(null);
  const [isVisible, setIsVisible] = useState(false);

  const showModal = (message: string, onConfirm: () => void, onCancel?: () => void) => {
    setModalContent(
      <div className="modal">
        <p>{message}</p>
        <button onClick={() => { onConfirm(); hideModal(); }}>Да</button>
        <button onClick={() => { onCancel && onCancel(); hideModal(); }}>Нет</button>
      </div>
    );
    setIsVisible(true);
  };

  const hideModal = () => {
    setIsVisible(false);
    setModalContent(null);
  };

  return (
    <ModalContext.Provider value={{ showModal, hideModal, modalContent, isVisible }}>
      {children}
      {isVisible && modalContent}
    </ModalContext.Provider>
  );
};

export const useModal = (): ModalContextProps => {
  const context = useContext(ModalContext);
  if (context === undefined) {
    throw new Error('useModal must be used within a ModalProvider');
  }
  return context;
};
